let tbody = document.querySelector('tbody')
axios({
    url: '/score/list',
    method: 'GET'
}).then(({ data }) => {
    let str = ''
    for (let key in data) {
        str += `<tr data-id='${key}'>
                <th scope="row">${key}</th>
                <td>${data[key].name}</td>
                <td class="score" data-batch='1'>${data[key].score[0]}</td>
                <td class="score" data-batch='2'>${data[key].score[1]}</td>
                <td class="score" data-batch='3'>${data[key].score[2]}</td>
                <td class="score" data-batch='4'>${data[key].score[3]}</td>
                <td class="score" data-batch='5'>${data[key].score[4]}</td>
                </tr>`
    }
    tbody.innerHTML = str
})

tbody.addEventListener('click', function (e) {
    if (e.target.className == 'score') {
        let td = e.target
        let input = document.createElement('input')
        input.value = td.innerHTML
        td.innerHTML = ''
        td.appendChild(input)
        // 自动获取焦点 ？ 下课的时候查找资料
        input.focus()
        // 让内容选中
        input.select()
        // 如果当前输入框失焦，则应该移除这个输入框
        input.addEventListener('blur', function () {
            td.innerHTML = input.value
        })
        // 按下enter录入或修改
        input.addEventListener('keydown', function (e) {
            if (e.key == 'Enter') {
                axios({
                    url: '/score/entry',
                    method: 'POST',
                    data: {
                        stu_id: td.parentNode.dataset.id,
                        batch: td.dataset.batch,
                        score: e.target.value
                    }
                }).then(data => {
                    if (data.code == 0) {
                        toastr.success(data.message)
                    } else {
                        toastr.error(data.message)
                    }
                })
            }
        })
    }
})